import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Publication } from '../../entity/publication.entity';
import { Repository } from 'typeorm';

@Provide()
export class PublicationService {

  @Inject()
  ctx: Context;

  @InjectEntityModel(Publication)
  entityModel: Repository<Publication>

  /** 
   * 创建 
   */
  async create(publication: Publication): Promise<Publication> {
    return this.entityModel.save(publication);
  }

  /**
   * 
   * @param pageNo 第几页
   * @param pageSize 每页大小
   * @returns 查询结果
   */
  async findAll(pageNo: number, pageSize: number): Promise<any> {
    const skip = (pageNo - 1) * pageSize;
    const [data, total] = await this.entityModel.findAndCount({
      where: {
        isDeleted: 0
      },
      take: pageSize,
      skip,
    });
    return {
      success: true,
      data,
      total
    };
  }

  /**
   * 
   * @param uuid 查询的 uuid
   * @returns 
   */
  async findOne(uuid: string): Promise<Publication> {
    return this.entityModel.findOneBy({ uuid, isDeleted: 0 });
  }

  async update(uuid: string, publication: Partial<Publication>): Promise<Publication> {
    await this.entityModel.update({ uuid }, publication);
    return this.entityModel.findOneBy({ uuid });
  }

  async remove(uuid: string): Promise<void> {
    await this.entityModel.update({ uuid }, { isDeleted: 1 });
  }
}
